#include "databaseengine.h"
#include<mutex>
#include<QList>

static std::once_flag       init_flag;
static DatabaseEngine* m_DatabaseEngine = nullptr;

DatabaseEngine *DatabaseEngine::Instance()
{
    std::call_once(init_flag, [&](){
        m_DatabaseEngine = new DatabaseEngine();
    });

    return m_DatabaseEngine;
}

void DatabaseEngine::log(QString userid, QString pwd)
{
    m_databaseinterface->log(userid,pwd);
    passwordpair = m_databaseinterface->getPasswordPair();
    if(passwordpair){
        m_databaseinterface->persondata(userid);
        m_persondata = m_databaseinterface->getpersondata();
        emit persondataChanged();
    }

    emit passwordPairChanged();
}

bool DatabaseEngine::getPassword()
{
    if(passwordpair){
        m_databaseinterface->setCurriculum();
        emit curriculumChanged();
    }
    return passwordpair;
}

Person *DatabaseEngine::getPersondata()
{

    return m_persondata;
}

void DatabaseEngine::rememberlocal(QString id, QString pwd)
{
    m_databaseinterface->setLocal(id,pwd);
}

Login *DatabaseEngine::getLocal()
{
    m_databaseinterface->seachLocal();
    m_local = m_databaseinterface->getLocal();
    return m_local;
}

void DatabaseEngine::setPersondata(QString id, QString phone, QString email)
{
    m_databaseinterface->setPersondata(id,phone,email);
    emit persondataChanged();
}

void DatabaseEngine::setChangedPassword(QString pwd)
{
    QString id = m_local->id;
    m_databaseinterface->setChangedPasswod(pwd,id);
}

QQmlListProperty<Curriculum> DatabaseEngine::getCurriculum()
{
    m_curriculum = m_databaseinterface->getCurriculum();
    QList<Curriculum*> list;
    for(int i=0;i<m_curriculum.size();i++){
        list.append(&m_curriculum[i]);
    }
    return QQmlListProperty<Curriculum>(this,list);
}

void DatabaseEngine::joinCurriculum(int cur_id)
{
    int id = (m_local->id).toInt();
    m_databaseinterface->joinCurriculum(id,cur_id);
    isSelectCur(cur_id);
}

void DatabaseEngine::isSelectCur(int cur_id)
{
    m_databaseinterface->isSelectCur((m_local->id).toInt(),cur_id);
    emit getIsSelectCur();
}

bool DatabaseEngine::getIsSelectCur()
{
    bool tmp = false;
    tmp = m_databaseinterface->getIsSelectCur();
    return tmp;
}

void DatabaseEngine::setMyCurriculum()
{
    m_databaseinterface->setMyCurriculum((m_local->id).toInt());
}

QQmlListProperty<Curriculum> DatabaseEngine::getMyCurriculum()
{
    m_curriculum = m_databaseinterface->getMyCurriculum();
    QList<Curriculum*> list;
    for(int i=0;i<m_curriculum.size();i++){
        list.append(&m_curriculum[i]);
    }
    return QQmlListProperty<Curriculum>(this,list);
}

DatabaseEngine::DatabaseEngine()
{
    m_databaseinterface = DatabaseInterface::Insterce();
}
